package com.usian.article.listener;

import com.alibaba.fastjson.JSON;
import com.usian.article.service.ApArticleService;
import com.usian.model.common.constants.HotArticleConstants;
import com.usian.model.mess.app.ArticleVisitStreamMess;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 功能描述：接受来自kafka的消息
 */
@Component
public class HotArticleKafkaListener {


    @Autowired
    private ApArticleService apArticleServiceI;


    /**
     * 功能描述：处理用户行为记分
     */
    @KafkaListener(topics = {HotArticleConstants.HOT_ARTICLE_INCR_HANDLE_TOPIC})
    public void listenNewsScan(ConsumerRecord<?,?> consumerRecord){
        // 优雅地处理null的，避免空指针异常
        Optional<? extends ConsumerRecord<?, ?>> recordOptional = Optional.ofNullable(consumerRecord);
        if (recordOptional.isPresent()) {
            ArticleVisitStreamMess mess =
                    JSON.parseObject(consumerRecord.value().toString(), ArticleVisitStreamMess.class);
            // 处理
            apArticleServiceI.handleHotArticle(mess);
        }
    }
}
